import { useLoadMore as vueRequestUseLoadMore } from 'vue-request';
import { request } from '@/lib';
import { BaseApi, BaseList, BaseListFrom } from '@/types/api/base';
/**
 * 加载更多hook
 * @example const { list } = useLoadMores(getXList)
 */
export const useLoadMore = <ResultType>(api: string, form?: Record<string, any>, otp: { success?: Function, error?: Function } = {}) => {
    const { success, error } = otp

    async function service(data?: { page: number }) {
        const _page = data?.page ? data.page + 1 : 1;
        const params: BaseListFrom = {
            ...form ?? {},
            page: _page,
        }
        if (!params.limit) params.limit = 10
        const res = await request.get<BaseList<ResultType>>(api, params)
        return {
            list: res.data.data.list,
            page: _page,
            total: res.data.data.total,
        };
    }

    const { data, loadingMore, dataList, loading, noMore, loadMore, loadMoreAsync, refresh, refreshAsync, mutate, cancel } = vueRequestUseLoadMore(service, {
        isNoMore: data => {
            return data?.list.length === data?.total;
        },
        onSuccess: res => {
            success && success(res)
        },
        onError: res => {
            error && error(res)
        }
    });
    return {
        /**列表数据 */
        list: dataList,
        /**是否请求中 */
        loading,
        /**是否正在加载更多 */
        loadingMore,
        /**与 loadMore 用法一致，但返回的是 Promise，需要自行处理异常 */
        loadMoreAsync,
        /**请求加载更多 */
        loadMore,
        /**请求结果数据 */
        res: data,
        /**是否有更多数据 */
        noMore,
        /**重新加载第一页数据 */
        refresh,
        /**与 refresh 用法一致，但返回的是 Promise，需要自行处理异常 */
        refreshAsync,
        /**直接修改 请求结果数据 的结果 */
        mutate,
        /**取消请求 */
        cancel,
    }
}